<template>
  <div class="com-update-avatar">
    <img class="avatar" :src="image" ref="image" />
    <van-nav-bar
      class="tool-bar"
      left-text="取消"
      right-text="确认"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  props: {
    file: {
      type: File,
      required: true
    }
  },
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null
    }
  },
  mounted() {
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    getCroppedCanvas() {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob(blob => {
          resolve(blob)
        })
      })
    },
    async onConfirm() {
      this.$toast.loading({
        message: '修改中'
      })

      const file = await this.getCroppedCanvas()
      console.log(file)

      // 如果要求 Content-Type 是 multipart/form-data，则一定要提交 FormData 对象，专门用于文件上传的
      const formData = new FormData()
      formData.append('photo', file)
      await updateUserPhoto(formData)

      this.$emit('update-success', window.URL.createObjectURL(file))
      this.$toast.success('修改成功')
      this.$emit('close')
    }
  }
}
</script>

<style lang="less" scoped>
.tool-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000000;
  .avatar {
    display: block;
    max-width: 100%;
  }
}
</style>
